﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Xml.Linq;
using SLControlLibrary.Resources.Controls.Calendar.OutlookCalendar.BusinessObjects;
using SLControlLibrary.Resources.Controls.Calendar.OutlookCalendar.Common;

namespace SLControlLibrary.Resources.Controls.Calendar.OutlookCalendar.DataAccess
{
    public class AppointmentProvider
    {
        #region Variables

        public OptionsDataProvider _OptionsProvider;
        private XDocument xDoc = null;

        #endregion

        #region Event Variables

        public event EventHandler OptionsLoaded;

        #endregion

        #region Constructor

        public AppointmentProvider()
        {
            _OptionsProvider = new OptionsDataProvider();
        }

        #endregion

        #region Events

        #region RequestXML_Completed

        private void RequestXML_Completed(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                xDoc = XDocument.Parse(e.Result);
                GetAppointmentValueList();
            }
        }

        #endregion

        #region wc_OpenWriteCompleted

        private void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                byte[] fileContent = e.UserState as byte[];
                System.IO.Stream outputStream = e.Result;
                outputStream.Write(fileContent, 0, fileContent.Length);
                outputStream.Close();

                GetAppointmentValueList();
            }
        }

        #endregion

        #endregion

        #region Methods

        #region RequestXML

        public void RequestXML(string AppointmentProfile)
        {
            WebClient _Client = new WebClient();
            _Client.DownloadStringAsync(new Uri(AppointmentProfile + "AppointmentOptions.xml", UriKind.RelativeOrAbsolute));
            _Client.DownloadStringCompleted += RequestXML_Completed;
        }

        #endregion

        #region GetAppointmentValueList

        private void GetAppointmentValueList()
        {
            AppointmentValueList _IList = new AppointmentValueList();

            foreach (XElement _Item in xDoc.Element("Appointments").Element("Settings").Elements("Add"))
            {
                AppointmentValue _AppValue = new AppointmentValue();
                _AppValue.ID = Int32.Parse(_Item.Attribute("id").Value);
                _AppValue.Value = (Enumerations.AppointmentValueOptions)Enum.Parse(typeof(Enumerations.AppointmentValueOptions), _Item.Attribute("value").Value, true);
                _AppValue.Color = SLControlLibrary.Resources.Common.Utility.ConvertStringToColor(_Item.Attribute("color").Value);

                _IList.Add(_AppValue);
            }

            _OptionsProvider.AppointmentValueList = _IList;

            GetAppointmentList();
        }

        #endregion

        #region GetAppointmentList

        private void GetAppointmentList()
        {
            AppointmentList _IList = new AppointmentList();

            foreach (XElement _Item in xDoc.Element("Appointments").Element("Values").Elements("Appointment"))
            {
                AppointmentValue appointmentValue = new AppointmentValue();
                var valueAttribute = _Item.Attribute("value");
                if (valueAttribute != null && valueAttribute.Value != null && valueAttribute.Value.Length > 0)
                {
                    appointmentValue =
                        _OptionsProvider.AppointmentValueList.Where(
                            (AppointmentValue n) => n.ID == Int32.Parse(_Item.Attribute("value").Value)).Single();
                }

                Appointment _Appointment = new Appointment(Int32.Parse(_Item.Attribute("id").Value),
                                                           DateTime.Parse(_Item.Attribute("startdate").Value),
                                                           DateTime.Parse(_Item.Attribute("enddate").Value),
                                                           TimeSpan.Parse(_Item.Attribute("starttime").Value),
                                                           TimeSpan.Parse(_Item.Attribute("endtime").Value),
                                                           appointmentValue,
                                                           _Item.Attribute("desc").Value);

                _IList.Add(_Appointment);
            }

            _OptionsProvider.AppointmentList = _IList;

            if (OptionsLoaded != null)
                OptionsLoaded(this, null);
        }

        #endregion

        #region SaveXML

        public void SaveXML(string AppointmentProfile, Appointment app)
        {
            if (xDoc != null)
            {
                xDoc.Element("Appointments").Element("Values").RemoveAll();

                if (app.IsNewAppointment)
                    _OptionsProvider.AppointmentList.Add(app);
                else
                {
                    foreach (Appointment _App in _OptionsProvider.AppointmentList)
                    {
                        if (_App.ID == app.ID)
                        {
                            _App.StartDate = app.StartDate;
                            _App.EndDate = app.EndDate;
                            _App.StartTime = app.StartTime;
                            _App.EndTime = app.EndTime;
                            _App.Desc = app.Desc;
                        }
                    }
                }

                foreach (Appointment _App in _OptionsProvider.AppointmentList)
                {
                    XElement _NewItem = new XElement("Appointment");

                    XAttribute _NewAtt = null;

                    if (_App.IsNewAppointment)
                    {
                        int _NewID = _OptionsProvider.AppointmentValueList.Max((AppointmentValue n) => n.ID) + 1;
                        _NewAtt = new XAttribute("id", _NewID.ToString());
                    }
                    else
                        _NewAtt = new XAttribute("id", _App.ID);

                    _NewItem.Add(_NewAtt);

                    _NewAtt = new XAttribute("startdate", _App.StartDate.Value.ToShortDateString());
                    _NewItem.Add(_NewAtt);

                    _NewAtt = new XAttribute("enddate", _App.EndDate.Value.ToShortDateString());
                    _NewItem.Add(_NewAtt);

                    _NewAtt = new XAttribute("starttime", _App.StartTime.Hours + ":" + _App.StartTime.Minutes);
                    _NewItem.Add(_NewAtt);

                    _NewAtt = new XAttribute("endtime", _App.EndTime.Hours + ":" + _App.EndTime.Minutes);
                    _NewItem.Add(_NewAtt);

                    _NewAtt = new XAttribute("desc", _App.Desc);
                    _NewItem.Add(_NewAtt);

                    _NewAtt = new XAttribute("value", _App.Value.ID.ToString());
                    _NewItem.Add(_NewAtt);

                    xDoc.Element("Appointments").Element("Values").Add(_NewItem);
                }

                byte[] fileContent = System.Text.Encoding.UTF8.GetBytes(xDoc.ToString());

                WebClient wc = new WebClient();
                wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
                Uri u = new Uri(Application.Current.Host.Source, "../FileUpload.ashx/?filename=" + AppointmentProfile + "AppointmentOptions.xml");
                wc.OpenWriteAsync(u, null, fileContent);
            }
        }

        #endregion

        #endregion
    }
}